package com.app.controller;

import com.app.model.AdminUserModel;
import com.app.model.LoanModel;
import com.app.model.UserModel;
import com.app.service.AdminUserService;
import com.app.service.LoanService;
import com.app.service.UserService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Action;

@Controller
@RestController
public class LoanController {
    @Autowired
    private LoanService loanService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminUserService adminUserService;

    //新增创业贷款信息
    @PostMapping("/insertLoanInfo")
    public Result<Object> insertLoanInfo(@RequestBody LoanModel model, HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        model.setCreateTime(CommonHelp.getNowTimestamp());
        loanService.insertLoanInfo(model);
        return Result.success("成功");
    }

    //按时间筛选 分页查询
    @GetMapping("/selectLoanList")
    public Result<Object> selectLoanList(Integer page, Integer limit, String startTime, String endTime, HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        return Result.success(loanService.selectLoanList(page, limit, startTime, endTime));
    }
}
